package com.young.common.util;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件下载工具类
 * Created by rookie on 2018/5/20.
 */
public class FileDownloadUtil {

    /**
     * 设置待下载的中文文件名,对IE做兼容处理
     * @param response 响应对象
     * @param fileName 文件名
     */
    public static void setFileNameOfCN(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        String userAgent = request.getHeader("User-Agent");//浏览器信息
        //存在MSIE关键字,则是IE系列浏览器(IE11以后,取消掉了msie关键字),没有Chrome/Safari/Firefox/AppleWebKit/Opera等关键字,默认按照IE处理
        if(userAgent != null && ( userAgent.contains("MSIE") || (!userAgent.contains("Chrome") && !userAgent.contains("Safari")
                && !userAgent.contains("Firefox") && !userAgent.contains("AppleWebKit") && !userAgent.contains("Opera")) ) ){
            //IE系浏览器下载时要对中文做编码处理(测试谷歌也可以这样,火狐会直接显示编码)
            response.setHeader("Content-disposition", "attachment; filename=" + new String(URLEncoder.encode(fileName, "UTF-8")));
        }else{//非ie的下载处理
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        }
    }

    /**
     * 文件下载通用处理
     * @param input 输入流,例如文件流等
     * @param fileName 文件名
     * @param request 请求对象,用来兼容浏览器
     * @param response 响应对象
     * @throws IOException
     */
    public static void downloadHandle(InputStream input, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (input != null){
            response.setContentType("application/x-msdownload;");//文件下载类型
            FileDownloadUtil.setFileNameOfCN(request, response, fileName);//设置中文文件名
            OutputStream os = response.getOutputStream();
            IOUtils.copy(input, os);//拷贝到输出流
        }
    }
}
